package com.xzzz.irda.auth.core.authorization;

import com.xzzz.irda.auth.core.token.AccessToken;
import com.xzzz.irda.auth.core.filter.AuthFilterProxy;
import com.xzzz.irda.auth.core.filter.impl.AuthorizationValidateFilter;

import java.util.List;
import java.util.Map;

/**
 * 授权上下文
 *
 * ThreadLocal 特性, 使用完后需要删除, 否则可能出现内存溢出
 *
 * https://www.yuque.com/docs/share/51fcaa07-2a73-4648-9dc1-6464999d7ed8?# 《ThreadLocal 原理》
 *
 * 设置: {@link AuthorizationValidateFilter#setAuthContext(Authorization)}
 * 删除: {@link AuthFilterProxy#doFilter(Authorization)}
 *
 * @author wangyf
 *
 */
public class AuthContext {

    private static final ThreadLocal<Authorization> AUTH_CONTEXT = new ThreadLocal<>();

    // region

    /**
     * 获取授权上下文
     * @return 授权信息
     */
    public static Authorization getContext (){
        return AUTH_CONTEXT.get();
    }

    /**
     * 设置上下文信息
     * @param authorization 授权信息
     */
    public static void setContext (Authorization authorization) {
        AUTH_CONTEXT.set(authorization);
    }

    /**
     * 删除上下文
     */
    public static void removeContext () {
        AUTH_CONTEXT.remove();
    }

    /**
     * 获取token 信息
     * @return token
     */
    public static AccessToken getToken () {
        if (AUTH_CONTEXT.get() == null) {
            return null;
        }
        return AUTH_CONTEXT.get().getAccessToken();
    }

    /**
     * 获取权限列表
     * @return 权限列表
     */
    public static List<String> getPermission () {
        return getContext().getPermissions();
    }

    // endregion

    /**
     * 获取UID
     * @return 用户ID
     */
    public static Long getUserId () {
        if (getToken() == null) {
            return null;
        }
        return getToken().getUserId();
    }

    /**
     * 获取BID
     *
     * @return 商铺 ID
     */
    public static Map<String,String> getUserMetadata() {
        return getToken().getMetadata();
    }

    /**
     * 用户用户ID及用户名
     */
    public static String getNameAndId() {
        String nameAndId = "";
        try {
            nameAndId = getUserMetadata().get("username") + "," + getUserId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nameAndId;
    }
}
